package ld.oauth.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ld.common.ResultInfoFactory;
import ld.oauth.blog.model.po.user.SysUser;
import ld.oauth.blog.service.user.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;



@Controller
public class MainController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping({"/index","/",""})
    public String index(Map<String,Object> map){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal !=null&&principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails)principal;
            String username = userDetails.getUsername();
            map.put("username",username);
        }
        return "index";
    }

    @RequestMapping("/user/info")
    @ResponseBody
    public Object userInfo(Authentication authentication){
        return authentication.getPrincipal();
    }

    @RequestMapping("/user/info2")
    @ResponseBody
    public Object userInfo(@AuthenticationPrincipal UserDetails userDetails){
        return userDetails;
    }

    @RequestMapping("/simple")
    public String simple(){
        return "simple";
    }

    //    /**
//     * 返回值为200则有权限
//     * @param id
//     * @return
//     */
//    @GetMapping("/{id}")
//    @PostAuthorize("returnObject.code==200")
//    public ResultInfoFactory deleteById(@PathVariable Long id) {
//        return ResultInfoFactory.success();
//    }
//
//    @GetMapping("/batch/{ids}")// -1,0,1,2
//    @PreFilter(filterTarget = "ids",value = "filterObject > 0")
//    public ResultInfoFactory deleteByIds(@PathVariable List<Long> ids) {
//        return ResultInfoFactory.success();
//    }

    @PreAuthorize("hasAuthority('sys:user:list')")
    @PostMapping("/page")
    @ResponseBody
    public ResultInfoFactory page(Page<SysUser> page, SysUser sysUser){
        return ResultInfoFactory.success(sysUserService.selectPage(page, sysUser));
    }

}
